const express = require('express')
const multer = require('multer')
const path = require('path')
const fs = require('fs')
const sharp = require('sharp')

const router = express.Router()

// 确保上传目录存在
const uploadDir = path.join(__dirname, '../../uploads')
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir, { recursive: true })
}

// 配置multer存储
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    // 按日期创建子目录
    const date = new Date()
    const dateDir = `${date.getFullYear()}${String(date.getMonth() + 1).padStart(2, '0')}${String(date.getDate()).padStart(2, '0')}`
    const targetDir = path.join(uploadDir, dateDir)
    
    if (!fs.existsSync(targetDir)) {
      fs.mkdirSync(targetDir, { recursive: true })
    }
    
    cb(null, targetDir)
  },
  filename: function (req, file, cb) {
    // 生成唯一文件名
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
    const ext = path.extname(file.originalname)
    cb(null, 'img-' + uniqueSuffix + ext)
  }
})

// 文件过滤器
const fileFilter = (req, file, cb) => {
  // 只允许图片
  const allowedTypes = /jpeg|jpg|png|gif|webp/
  const extname = allowedTypes.test(path.extname(file.originalname).toLowerCase())
  const mimetype = allowedTypes.test(file.mimetype)
  
  if (mimetype && extname) {
    return cb(null, true)
  } else {
    cb(new Error('只支持上传图片文件（jpg, png, gif, webp）'))
  }
}

const upload = multer({
  storage: storage,
  fileFilter: fileFilter,
  limits: {
    fileSize: 10 * 1024 * 1024 // 限制10MB
  }
})

/**
 * 上传单张图片
 * POST /api/upload/image
 */
router.post('/image', upload.single('image'), async (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).json({ 
        success: false, 
        message: '请选择要上传的图片' 
      })
    }

    const file = req.file
    const imageUrl = `/uploads/${path.basename(path.dirname(file.path))}/${file.filename}`

    // 可选：压缩图片（如果图片宽度超过1200px）
    try {
      const metadata = await sharp(file.path).metadata()
      if (metadata.width > 1200) {
        await sharp(file.path)
          .resize(1200, null, {
            fit: 'inside',
            withoutEnlargement: true
          })
          .toFile(file.path + '.tmp')
        
        // 替换原文件
        fs.renameSync(file.path + '.tmp', file.path)
      }
    } catch (error) {
      console.error('图片压缩失败:', error)
      // 压缩失败不影响上传
    }

    res.json({
      success: true,
      message: '上传成功',
      data: {
        filename: file.filename,
        originalname: file.originalname,
        size: file.size,
        url: imageUrl,
        path: file.path
      }
    })
  } catch (error) {
    console.error('上传错误:', error)
    res.status(500).json({
      success: false,
      message: error.message || '上传失败'
    })
  }
})

/**
 * 上传多张图片
 * POST /api/upload/images
 */
router.post('/images', upload.array('images', 10), async (req, res) => {
  try {
    if (!req.files || req.files.length === 0) {
      return res.status(400).json({
        success: false,
        message: '请选择要上传的图片'
      })
    }

    const images = req.files.map(file => {
      const imageUrl = `/uploads/${path.basename(path.dirname(file.path))}/${file.filename}`
      return {
        filename: file.filename,
        originalname: file.originalname,
        size: file.size,
        url: imageUrl,
        path: file.path
      }
    })

    // 批量压缩图片
    for (const file of req.files) {
      try {
        const metadata = await sharp(file.path).metadata()
        if (metadata.width > 1200) {
          await sharp(file.path)
            .resize(1200, null, {
              fit: 'inside',
              withoutEnlargement: true
            })
            .toFile(file.path + '.tmp')
          
          fs.renameSync(file.path + '.tmp', file.path)
        }
      } catch (error) {
        console.error('图片压缩失败:', error)
      }
    }

    res.json({
      success: true,
      message: `成功上传${images.length}张图片`,
      data: images
    })
  } catch (error) {
    console.error('批量上传错误:', error)
    res.status(500).json({
      success: false,
      message: error.message || '上传失败'
    })
  }
})

/**
 * 删除图片
 * DELETE /api/upload/:filename
 */
router.delete('/:dateDir/:filename', (req, res) => {
  try {
    const { dateDir, filename } = req.params
    const filePath = path.join(uploadDir, dateDir, filename)

    if (fs.existsSync(filePath)) {
      fs.unlinkSync(filePath)
      res.json({
        success: true,
        message: '删除成功'
      })
    } else {
      res.status(404).json({
        success: false,
        message: '文件不存在'
      })
    }
  } catch (error) {
    console.error('删除错误:', error)
    res.status(500).json({
      success: false,
      message: '删除失败'
    })
  }
})

module.exports = router

